package com.art.sunflower.controller;


import com.art.sunflower.exception.NullNewsException;
import com.art.sunflower.pojo.News;
import com.art.sunflower.service.NewsService;
import com.art.sunflower.util.AddFile;
import com.art.sunflower.util.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@CrossOrigin
@RequestMapping(value = "news")
@Api(value = "新闻公告")
public class NewsController {
    @Resource
    private NewsService newsService;

    @PostMapping("")
    @ResponseBody
    @RequiresRoles(value = {"admin"})
    @ApiOperation("增加一条新闻信息")
    public Message addNews(@RequestParam(value = "file", required = false) MultipartFile file, String title, String info, String author, String content) {
        Date currentTime = new Date();
        News news = null;
        if (file != null) {
            AddFile addFile = new AddFile();
            news = new News(addFile.addFile(file, "news"), title, info, currentTime, author, content);
        } else
            news = new News(title, info, currentTime, author, content);
        int count = newsService.addNews(news);
        if (count > 0) {
            return Message.createSuc("添加成功");
        }
        return Message.createErr("增加失败");
    }


    @DeleteMapping(value = "/{id}")
    @RequiresRoles(value = {"admin"})
    @ApiOperation("删除一条新闻信息")
    public Message deleteById(@PathVariable int id) {
        int count = newsService.deleteById(id);
        if (count > 0) {
            return Message.createSuc(count);
        }
        return Message.createErr("删除失败");
    }


    @GetMapping("newsList")
    @ApiOperation("分页获取新闻的列表")
    public Message getList(Integer pageSize, Integer pageNo) {
        try {
            return Message.createSuc(newsService.findAllNews(pageSize, pageNo));
        } catch (NullNewsException e) {
            e.printStackTrace();
            return Message.createErr("新闻不存在");
        }

    }

    @GetMapping(value = "/{id}")
    @ApiOperation("获取一个新闻信息")
    public Message selectById(@PathVariable int id) {
        if (newsService.selectById(id) == null) {
            return Message.createErr("编号不存在，查找失败");
        } else {
            return Message.createSuc(newsService.selectById(id));
        }
    }

}
